#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <iostream>
#include "udp_server.h"

udp_server::udp_server(int port ) {

	m_sockfd=socket(AF_INET,SOCK_DGRAM,0);

	bzero(&m_servaddr,sizeof(m_servaddr));
	m_servaddr.sin_family = AF_INET;
	m_servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
	m_servaddr.sin_port=htons(port);
	bind(m_sockfd,(struct sockaddr *)&m_servaddr,sizeof(m_servaddr));

	socklen_t slen;
	if(int i = getsockname(m_sockfd, (struct sockaddr *)&m_servaddr, &slen))
	{
		std::cout << "socket error =" << i << std::endl;
		exit(1);
	}
	m_port = ntohs(m_servaddr.sin_port);
}
int udp_server::getPort()
{
	return m_port;
}
com::Block udp_server::getBlock()
{
	while(1) {
		socklen_t len;
		char mesg[10000];
		len = sizeof(m_cliaddr);
		int byte_count = recvfrom(m_sockfd,mesg,10000,0,(struct sockaddr *)&m_cliaddr,&len);
		std::string data(mesg,byte_count);

		m_clientIP = m_cliaddr.sin_addr;

		com::Block block;
		block.ParseFromString(data);
		return block;
	}
}
struct in_addr udp_server::getClientIP()
{
	return m_clientIP;
}

